angular.module('whm.services', [])

/**
 * 实时库存清单
 */
.factory('InventoryService',function(){

  var getInventorySub = function(scope){
    return scope.subscribe('inventory');
  };

  return {
    //库存预警
    overview : function(scope,feild,callback){
      
      scope.helpers({
        inventory_alarm: function() {
          return Inventory.find(feild);
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_alarm){
          var lowInventory=0,outOfInventory=0;
          var overview={stat:0,statInfo:'',alarmHref:''};
          if(!scope.inventory_alarm.length){
            overview.stat=1;
            overview.statInfo = '充足';
            overview.alarmHref= 'all';
          }else{
            scope.inventory_alarm.forEach(function(item){
              if(item.total===0){
                outOfInventory++;
              }
              if(item.total>0){
                lowInventory++;
              }
            });
            if(outOfInventory>0){
              overview.stat=3;
              overview.statInfo += outOfInventory+'款缺货';
            }
            if(lowInventory>0){
              overview.stat=outOfInventory===0?2:3;
              overview.statInfo+=overview.statInfo!==''?', ':'';
              overview.statInfo += lowInventory+'款库存低';
            }
            overview.alarmHref= 'alarm';
          }
          callback(overview);
        }
      });
    },
    caclValue: function(scope,field,callback){
      scope.helpers({
        inventory_all: function() {
          return Inventory.find(field);
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_all){
          var totalValue=0;
          scope.inventory_all.forEach(function(item){
            // console.log(item);
            totalValue+=item.sale_price;
          });
          callback(totalValue);
        }
      });
    },

  /**
   * 列出库存商品
   */
    list: function(scope,field,callback){
      scope.helpers({
        inventory_list: function() {
          return Inventory.find(field);
        }
      });
      scope.autorun(function() {
        if(getInventorySub(scope).ready() && scope.inventory_list){
          var subtotal = {'totalCount':0,'totalValue':0};
          scope.inventory_list.forEach(function(item){
            // 总数量
            subtotal.totalCount+=item.total;
            // 总价值
            subtotal.totalValue+=item.sale_price;
          });
          callback(scope.inventory_list,subtotal);
        }
     });
    }
  };
})
;
